<?php
/**
 * file video.php
 * Created on 2015-3-21 下午6:06:57 
 * Create by xiweijie
 */
namespace haibao\cms\data;

use \haibao\frame\data\query\Condition;
use \haibao\cms\model\filter\VideoCategory as VideoCategoryFilter;
use \haibao\cms\model\data\VideoCategory as VideoCategoryData;

class VideoCategory extends \haibao\cms\data\BaseMysql{
    
    private static $cacheCategoryTreeName = 'VideoCategoryTree';
    private static $cacheCategoryListName = 'VideoCategoryList';
    
    public function __construct(){
        parent::__construct('\haibao\cms\model\data\VideoCategory');
    }
    
    public function addVideoCategory($model){
        parent::add($model);
        $this->unsetCache(self::$cacheCategoryTreeName);
		$this->unsetCache(self::$cacheCategoryListName);
        return $model;
    }
    
    public function updateVideoCategoryById($model){
        $arrSet = array();
        if($model->CategoryName){
            $arrSet[VideoCategoryFilter::CONDITION_FIELD_NAME_CATEGORYNAME] = $model->CategoryName;
        }
        if($model->CategoryDesc){
            $arrSet[VideoCategoryFilter::CONDITION_FIELD_NAME_CATEGORYDESC] = $model->CategoryDesc;
        }
        if($model->PicId){
            $arrSet[VideoCategoryFilter::CONDITION_FIELD_NAME_PICID] = $model->PicId;
        }
        if($model->ParentId || $model->ParentId == 0){
            $arrSet[VideoCategoryFilter::CONDITION_FIELD_NAME_PARENTID] = $model->ParentId;
        }
        if($model->OrderNo || $model->OrderNo == 0){
        	$arrSet[VideoCategoryFilter::CONDITION_FIELD_NAME_ORDERNO] = $model->OrderNo;
        }
        
        $this->updateById($model->Id, $arrSet);
        $this->unsetCache(self::$cacheCategoryTreeName);
        $this->unsetCache(self::$cacheCategoryListName);
    }
    
   public function deleteVideoCategoryById($categoryId){
       $this->beginTranscation();
       try {
           $model = $this->getCategoryById($categoryId);
           	
           $childIds = $this->getChildCategoryById($categoryId);
           array_unshift($childIds, $categoryId);
           $str = preg_replace('/(\d+)/', '%s', implode(',', $childIds));
           	
           $sql = 'update `VideoCategory` set Status=%s where id in('.$str.')';
           	
           array_unshift($childIds, VideoCategoryData::STATUS_DELETE);
           $this->query($sql, $childIds);
           	
           $category = $this->getCategoryById($categoryId);
           $this->unsetCache(self::$cacheCategoryTreeName);
           $this->unsetCache(self::$cacheCategoryListName);
       } catch (\Exception $e) {
           $this->rollback();
           throw $e;
       }
       $this->endTranscation();
   }
   
   /**
    * 根据父级分类id查询下级分类的id
    */
   public function getChildCategoryById($id){
       if(!$id){
           return false;
       }
       $query = new VideoCategoryFilter();
       $query->where(VideoCategoryFilter::CONDITION_FIELD_NAME_PARENTID, Condition::CONDITION_EQUAL, $id);
       $models = $this->getAll($query);
   
       $retArr = array();
       while (count($models)){
           $model = array_shift($models);
           $arrModel = $model->toArray();
           array_push($retArr, $arrModel[VideoCategoryFilter::CONDITION_FIELD_NAME_ID]);
       }
   
       return $retArr;
   }
    
    /**
	 * 是否存在子分类
	 * @param int $id
	 */
	public function isExitstChildCategory($id){
		$sql = "select * from `VideoCategory` where Status = 1 and ParentId=%s";
		$result = $this->query($sql, array(intval($id)));
		$data = array();
		while ($row = $result->fetch_assoc()){
			$model = new \haibao\cms\model\data\VideoCategory();
			$model->loadArray($row);
			array_push($data, $model);
		}
		return count($data);
	}
    
    public function getCategoryTree(){
        $categoryTreeCache = $this->getCache(self::$cacheCategoryTreeName);
        return $categoryTreeCache ? unserialize($categoryTreeCache) : $this->setCategoryTree();
    }
    
    public function getCategoryById($categoryId){
        return parent::getOneById($categoryId);
    }
    
    private function setCategoryTree($return = true){
        $categoryTree = array();
        $categorysDict = $this->getAllCategoryList();
        if($categorysDict){
            foreach($categorysDict as $categoryDict){
                if(isset($categorysDict[$categoryDict[VideoCategoryFilter::CONDITION_FIELD_NAME_PARENTID]])){
                    $categorysDict[$categoryDict[VideoCategoryFilter::CONDITION_FIELD_NAME_PARENTID]]['children'][] = &$categorysDict[$categoryDict[VideoCategoryFilter::CONDITION_FIELD_NAME_ID]];
                }else{
                    $categoryTree[$categoryDict[VideoCategoryFilter::CONDITION_FIELD_NAME_ID]] = &$categorysDict[$categoryDict[VideoCategoryFilter::CONDITION_FIELD_NAME_ID]];
                }
            }
        }
        $categoryTree && $this->setCache(self::$cacheCategoryTreeName, serialize($categoryTree));
        if($return){
            return $categoryTree;
        }
    }
    
    public function getAllCategoryList(){
       $categoryListCache = $this->getCache(self::$cacheCategoryListName);
       if(!$categoryListCache){
		    $categoryListCache = $this->setAllCategorysDict();
		}
		return $categoryListCache;
    }
    
    private function setAllCategorysDict($return = true){
        $videoCategoryFilter = new VideoCategoryFilter();
    
        $videoCategoryFilter->where(VideoCategoryFilter::CONDITION_FIELD_NAME_STATUS, Condition::CONDITION_EQUAL, VideoCategoryData::STATUS_ENABLE);
		$videoCategoryFilter->order(VideoCategoryFilter::CONDITION_FIELD_NAME_ORDERNO);
        $categorysDict = $this->getAll($videoCategoryFilter);
        $categorysArr = array();
        if($categorysDict){
            foreach($categorysDict as  $key=>$categoryModel){
                $categorysArr[$categoryModel->Id] = $categoryModel->toArray();
            }
        }
        if($categorysArr){
            $this->setCache(self::$cacheCategoryListName, $categorysArr);
        }
        if($return){
            return $categorysArr;
        }
    }
    
}